;
(function() {
  new Vue({
    el: '#createCm',
    data: {
		lsListData: [],
		lsSelectData: [],
		
      type: [{
        name: '公司',
        type: 'QY'
      }, {
        name: '个人',
        type: 'PE'
      }],
      typeAct: 'QY',
      blacklist: [{
        name: '是',
        type: 'Y'
      }, {
        name: '否',
        type: 'N'
      }],
      blacklistAct: 'N',
      industryData: [],
      selectedIndustry:[],
      customerStateData: [
      ],
      selectedCustomerState:[],
      channelTypeData: [],
      selectedChannelType:[],
      channelNameData: [],
      allchannelNameData: [],
      selectedChannelName:[],
      selectedChannelNameVal:[],
      processData: [],
      selectedProcess:[],
      fieldData: [],
      customerData: {
        cincbInfo: {
          logoUrl: ''
        }
      },
      biz_info: {},
      //红色框框警告
      cmflag: false,
      cmstatusflag: false,
      industryflag: false,
      lspeopleflag: false,
      lsphoneflag: false,
      qdflag: false,
      qdnmflag: false,
      id: hlUrlUtil.GetQueryString('id'),
      validataflag: false,
      //模糊搜索结果
      cmNameList: '',
      // 是否显示模糊搜索结果
      showcmNameList: '',
      //选择公司的名称
      company_name: '',
      //工商信息
      IndustryDetail: {
        bizRegisterCode: '',
        operateStatus: '',
        socialUnifiedCreditCode: '',
        registerAgency: '',
        bizOrganizationCode: '',
        bizCompanyType: '',
        bizLegalPersonName: '',
        establishTime: '',
        registerCapital: '',
        operationEndTime: '',
        registerAddr: '',
        operationScope: '',
      },
      //预留工商编号
      reserceCode: '',
			//
			tmpData: [],
			resData: []
    },
    filters: {
      customerState(val) {
        let result;
        switch (val) {
          case 'PO':
            result = '潜在客户'
            break;
          case 'YX':
            result = '意向客户'
            break;
          case 'LS':
            result = '流失客户'
            break;
          case 'CJ':
            result = '成交客户'
            break;
		case 'ZD':
		  result = '重点客户'
		  break;
          case 'BL':
            result = '黑名单客户'
            break;
          default:
            result = '--'
        }
        return result
      }
    },
    mounted() {
      this.getIndustryData()
      this.getChannelTypeData()
      this.getChannelNameData()
      this.getProcessData()
      this.ZS_CUSTOMER_STATUS()
	  
	  this.getLsReason()
    },
    methods: {
		getLsReason() {
		  var that = this
		  hlhttp.get({
		    url: 'configure/dict',
		    data: {
		      module_code: 'ZHSH',
		      config_name: 'ZS_LOSS_REASON'
		    },
		    success: function (data) {		
				var temp = data.filter((item) => {return item.status == 'Y'})
		      that.lsListData = hlArrayUtil.replaceData(temp, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
		    },
		  })
		},
		
			ZS_CUSTOMER_STATUS() {
			    var self = this
			    hlhttp.get({
			        url: 'configure/dict',
			        data: { module_code: 'ZHSH', config_name: 'ZS_CUSTOMER_STATUS' },
			        success: data => {
			            self.customerStateData = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
			        }
			    })
			},
      inputChange() {
        var that = this
        setTimeout(function() {
          that.showcmNameList = false
        }, 1000)
      },
      //选择公司
      selectcmName(name) {
        this.customerData.name = name
        this.company_name = name
        this.getcompanyDetail()
      },
      //获取工商信息
      getcompanyDetail() {
        var self = this
        if (self.company_name) {
          hlhttp.get({
            url: 'customer/industry_and_commerce_info',
            data: { company_name: self.company_name },
            success: function(res){
              self.showcmNameList = false
              self.IndustryDetail = res

              if (!self.customerData.idcode) {
                self.customerData.idcode = self.IndustryDetail.socialUnifiedCreditCode
                self.reserceCode = self.IndustryDetail.socialUnifiedCreditCode
              }
            }
          })
        }
      },
      // 获取搜索结果
      //本地
      getcmNameList() {
        var self = this
        if (self.customerData.name) {
          hlhttp.get({
            url: 'customer/search_from_qxb',
            data: { customer_name: self.customerData.name,local_flag: 'Y'},
            success: function(res){
              self.cmNameList = res
              if (res) self.showcmNameList = true
            }
          })
        }
      },
      //第三方
      show: function(ev) {
        var self = this
        if (ev.keyCode == 13) {
          self.cmNameList = []
          if (self.cmName) {
            hlhttp.get({
              url: 'customer/search_from_qxb',
              data: { customer_name: self.cmName , local_flag: 'N' },
              success: function(res){
                self.cmNameList = res
                if (res) self.showcmNameList = true
              }
            })
          }
        }

      },
      //关闭弹窗
      hidePopValidata() {
        this.validataflag = false
      },
      selectedCustomerStateChange(){
        if(this.selectedCustomerState[0]!=='LS'){
          this.lsSelectData.splice(0,1)
        }
      },
      //验证客户
      validataCustomer() {
        if(!this.checkCustom()){
          hl.toast('请完成自定义字段')
          return
        }
       let self = this;
        this.cmflag = false;
        this.cmstatusflag = false;
        this.industryflag = false;
        this.lspeopleflag = false;
        this.lsphoneflag = false;
        this.qdflag = false;
        this.qdnmflag = false;
        if (!this.customerData.type) {
          this.cmflag = true;
          hl.toast('请填写客户名称')
          return
        }
        if (!this.selectedCustomerState.length) {
          // this.cmstatusflag = true;
          hl.toast('请选择客户状态')
          return
        }
        if (this.selectedCustomerState[0]=='LS' && !this.lsSelectData.length) {
          hl.toast('请选择流失原因')
          return
      }
        if (!this.customerData.lperson) {
          // this.lspeopleflag = true;
          hl.toast('请填写联系人')
          return
        }
        if (!this.customerData.phone) {
          // this.lsphoneflag = true;
          hl.toast('请填写联系电话')
          return
        }
        if (!this.selectedChannelType.length) {
          // this.qdflag = true;
          hl.toast('请选择渠道分类')
          return
        }
				
        hlhttp.get({
          url: 'customer/check_customer_repeat',
          data: {
            customer_id: this.id,
            customer_name: this.customerData.name,
            cstmr_contact: this.customerData.lperson,
            cstmr_contact_no: this.customerData.phone,
            customer_type: this.typeAct
          },
          success: function(res){
            if (res.repeat == 'N') self.postCm()
            if (res.repeat == 'Y') self.validataflag = true
          }
        })
      },
      getIndustryData() {
        var self = this
        hlhttp.get({
          url: 'configure/industry/dict',
          success: function(data){
            self.industryData = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
          }
        })
      },
      getChannelTypeData() {
        var self = this
        hlhttp.get({
          url: 'configure/dict',
          data: { module_code: 'ZHSH', config_name: 'ZS_CHANNEL_CATE' },
          success: function(data){
            let arr = []
            data.map(item =>{
              if(item.status == 'Y'){
                arr.push(item)
              }
            })
            self.channelTypeData = hlArrayUtil.replaceData(arr, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
          }
        })
      },
      getChannelNameData() {
        var self = this
        hlhttp.get({
          url: 'configure/dict',
          data: { module_code: 'ZHSH', config_name: 'ZS_CHANNEL_NAME'},
          success: function(data){
            self.allchannelNameData = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
            self.getCustomerInfo()
          }
        })
      },
      getProcessData() {
        var self = this
        hlhttp.get({
          url: 'configure/dict',
          data: { module_code: 'ZHSH', config_name: 'ZS_PROCESS_MANAGER'},
          success: function(data){
            self.processData = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
          }
        })
      },

      handleChannelTypeChange(data){
        this.channelNameData = []
        this.allchannelNameData.map(item =>{
          if(item.parentDictCode == data[0].dictCode){
            this.channelNameData.push(item)
          }
        })
        this.selectedChannelName = []
        this.selectedChannelTypeVal = data[0]['name'].split()
      },
      
      handleChannelNameChange(data){
        this.selectedChannelNameVal = data[0]['code'].split()
      },
			
			// 新的自定义字段
			resMake (type, val) {
				// text  textarea mobile email phone  time date  dateTime
				let t0 = ['text', 'email', 'area', 'mobile', 'phone', 'time', 'date', 'dateTime', 'select', 'radio', 'checkbox'];						
				let t1 = ['file'];
				if (t0.indexOf(type) > -1) return val;
				if (t1.indexOf(type) > -1) {
					let data = []
					if (val) {
						val.map(item => {
							data.push(item.response ? item.response : item)
						})
					}
					return data
				}
			},
			
			newFieldsData () {
				let data = [];
				this.resData.map(item => {
					data.push({
						component_code: item.code,
						component_type: item.type,
						property: this.resMake(item.type, item.value)
					})
				})
				return data;
			},

      postCm() {
        
				let self = this;
        var bizinfo = {
          "biz_register_code": this.IndustryDetail.bizRegisterCode || '#',
          "operate_status": this.IndustryDetail.operateStatus || '',
          "social_unified_credit_code": this.IndustryDetail.socialUnifiedCreditCode || '#',
          "register_agency": this.IndustryDetail.registerAgency || '#',
          "biz_organization_code": this.IndustryDetail.bizOrganizationCode || '#',
          "biz_company_type": this.IndustryDetail.bizCompanyType || '#',
          "biz_legal_person_name": this.IndustryDetail.bizLegalPersonName || '#',
          "operation_scope": this.IndustryDetail.operationScope || '#',
          "register_capital": this.IndustryDetail.registerCapital || '#',
          "establish_time": this.IndustryDetail.establishTime || '#',
          "register_addr": this.IndustryDetail.registerAddr || '#',
          "operation_end_time": this.IndustryDetail.operationEndTime || '#'
        };
        var data = {
          customer_id: this.id,
          type: this.customerData.type || '#',
          name: this.customerData.name || '#',
          industry: this.selectedIndustry.length ? this.selectedIndustry.join() : '#',
          lperson: this.customerData.lperson || '#',
          phone: this.customerData.phone || '#',
          channel_name_code: this.selectedChannelName.length ? this.selectedChannelName.join() : '#',
          channel_name_value: this.selectedChannelNameVal.length ? this.selectedChannelNameVal.join() : '#',
          channel_category_code: this.selectedChannelType.length ? this.selectedChannelType.join() : '#',
          customer_state: this.selectedCustomerState.length ? this.selectedCustomerState.join() : '#',
          memo: this.customerData.memo || '#',
          black_state: this.customerData.blackState || '#',
          idcode: this.customerData.idcode || '#',
          email: this.customerData.email || '#',
          short_name: this.customerData.shortName || '#',
          process_type: this.customerData.processType || '#',
          address: this.customerData.address || '#',
          zipcode: this.customerData.zipcode || '#',
          custom_config_property: JSON.stringify(this.fieldData),
					page_customize_component_biz_content: JSON.stringify(this.newFieldsData()),
          biz_info: JSON.stringify(bizinfo),
		  loss_reason: this.lsSelectData && this.lsSelectData.length ? this.lsSelectData[0] : '#'
        }
        hlhttp.put({
          url: 'customer',
          data,
          success: function(){
            hl.toast('编辑成功')
            hlUrlUtil.goTo('customerDetails', { id: self.id,ddtab: true,page: 'customerManagement' })
          }
        })
      },
      	// 检测自定义字段填写是否符合要求
        checkCustom() {
          let flag = true
          this.resData.map(item => {
          	if (item.requiredFlag == 'Y' && (!item.value || !item.value.length) && item.type != 'line') {
          	  flag = false
          	}
          })	
          return flag
        },
      //自定义字段获取
      marketCustomizeDt (val) {
        var that = this
				return
      	hlhttp.get({
      		url: 'configure/customize_column',
      		data: {
      		  module: 'ZHSH',
      		  config_name: 'ZS_CUSTOMIZE_COLUMNS',
      		},
      		success: (res) => {
            let arr = [...res.customizeColumns, ...res.systemColumns]
            for (var i = arr.length - 1; i >= 0; i--) {
              if (arr[i].isValid == 'false') {
                arr.splice(i,1)
              }
						}//去除多余数据（未启动，无关联）
						// if(val){
            //   arr = hlArrayUtil.removeRepeat([...val,...arr], 'configCode');
            // }
            console.log(arr)
             //若有合同详情，则合并,去重（保留合同）
            let textList = []
            let noTextList = []
            arr.map((item,index) =>{
              if(item.fieldType == 'text'){
                textList.push(item)
              }else{
                noTextList.push(item)
              }
            })
            arr = [...noTextList,...textList]
            //重新排序，将文本类型放到最后
            console.log(arr)
            arr.map(item => {
              if(!item.select){
                if (item.fieldType == 'radio' || item.fieldType == 'checkbox' || item.fieldType == 'select') {
                  item.select = [];
                  item.selectArr = item.fieldRange.split(',')
                  item.selectArrCopy = []
                  item.selectArr.map(item0 => {
                    item.selectArrCopy.push({
                      name: item0,
                      code: item0
                    })
                  })
  
                } else {
                  item.select = '';
                }
              }
            })
            if(val){
              val.map(item =>{
                arr.map(single =>{
                  if(single.configCode == item.configCode){
                    single.select = item.select
                  }
                })
              })
            }
      			that.fieldData = arr
      		}
      	})
      },
      getCustomerInfo:function() {
        var self = this
        hlhttp.get({
          url: 'customer,cincb_info',
          data: { customer_id: this.id },
          success: function(res){
												//新的自定义字段
						self.tmpData = res.pageCustomizeComponentBizContentList ? res.pageCustomizeComponentBizContentList : []
						
						
            if (!res.cincbInfo) {
              self.IndustryDetail = {
                bizRegisterCode: '',
                operateStatus: '',
                socialUnifiedCreditCode: '',
                registerAgency: '',
                bizOrganizationCode: '',
                bizCompanyType: '',
                bizLegalPersonName: '',
                establishTime: '',
                registerCapital: '',
                operationEndTime: '',
                registerAddr: '',
                operationScope: '',
              }
            } else {
              self.IndustryDetail = res.cincbInfo
            }

            self.company_name = res.name

            if (!res.cincbInfo) {
              res.cincbInfo = {}
              res.cincbInfo.logoUrl = 'http://dev.fenzhitech.com/res/8e694146ea6e7ed53310514f7324942e.jpg'
            }
            if (res.cincbInfo) {
              if (!res.cincbInfo.logoUrl) {
                res.cincbInfo.logoUrl = 'http://dev.fenzhitech.com/res/8e694146ea6e7ed53310514f7324942e.jpg'
              }
            }

            self.customerData = res

            if (res.channelCategoryCode) {
              self.selectedChannelType.push(res.channelCategoryCode)
              self.channelNameData = []
              self.allchannelNameData.map(item => {
                if (item.parentDictCode == res.channelCategoryCode) {
                  self.channelNameData.push(item)
                }
              })
              
            }
            let isHold = false
            self.channelNameData.map(item =>{
              if(item.dictCode == res.channelNameCode){
                isHold = true
              }
            })
            if(isHold) self.selectedChannelName.push(res.channelNameCode)
            if(res.channelNameVal) self.selectedChannelNameVal.push(res.channelNameVal)

            self.selectedCustomerState.push(res.customerState)
			
			if (res.lossReason) {self.lsSelectData.push(res.lossReason)}
            self.selectedIndustry.push(res.industry)
            self.selectedProcess.push(res.processType)
            self.marketCustomizeDt(res.customConfigProperty ? JSON.parse(res.customConfigProperty) : [])
          }
        })
      }
    }

  })
}())
